<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\index\middleware;

use think\Exception;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Env;

class MallToken
{
    //数据库连接
    public function handle($request, \Closure $next){
        //以header上带的token为主,参数上的token为次: key名mallToken
        $affiliation = Env::get("affiliation");
        if ($affiliation == 'saas'){
            if (request()->controller() == "Notify"){
                $token = $request->route('mallToken');
            }else{
                $token = request()->header('mallToken');
                if (empty($token)){
                    $token = request()->get('mallToken');
                    if (empty($token)){
                        throw new Exception("请求参数有误",HTTP_UNAUTH);
                    }
                }
            }

            if (!Cache::store('redis')->has($token)){
                throw new Exception("请求参数有误",HTTP_UNAUTH);
            }
            $mall = Cache::store('redis')->get($token);

            global $mallId,$mallToken;
            $mallId = $mall;
            $mallToken = $token;
        }

        return $next($request);
    }
}